import { App, defineComponent, ComponentOptions } from "vue";
import locale from "./locale";
export const getPropByPath = (obj: any, keyPath: string) => {
  try {
    return keyPath.split(".").reduce((prev, curr) => prev[curr], obj);
  } catch (error) {
    return "";
  }
};
export const isFunction = (val: unknown): val is Function =>
  typeof val === "function";

export function createComponent(name: string) {
  // TODO: It will be deprecated someday.
  const componentName = "nut-" + name;
  return {
    componentName,
    translate(keyPath: string, ...args: unknown[]): string {
      // 依赖响应能力
      const languages = locale.languages();
      const text =
        getPropByPath(languages, `${name.replace("-", "")}.${keyPath}`) ||
        getPropByPath(languages, keyPath);
      return isFunction(text) ? text(...args) : text;
    },
    create: function (_component: ComponentOptions) {
      _component.name = componentName;
      _component.install = (vue: App) => {
        vue.component(_component.name as string, _component as any);
      };
      return defineComponent(_component as ComponentOptions);
    } as typeof defineComponent,
  };
}
